var express = require('express');
var router = express.Router();

//引入连接数据库模块
const conn = require('../conn')

//连接数据
conn.connect(() => {})
var jsonWrite = function(res, ret) {
    if (typeof ret === 'undefined') {
        res.json({
            code: '1',
            msg: '操作失败'
        });
    } else {
        res.json(
            ret
        );
    }
};
//用户注册
router.post('/addUser', (req, res) => {
    var sql = 'insert into users(userName,userPwd,Phone) values (?,?,?)';
    var params = req.body;
    conn.query(sql, [params.userName, params.userPwd, params.Phone], function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result) {
            jsonWrite(res, result);
        }
    })
});
// 判断是否注册
router.get('/isReg', (req, res) => {
    let { Phone } = req.query;
    const sqlStr = `select * from users where  Phone='${Phone}'`;
    conn.query(sqlStr, (err, result) => {
        if (err) {
            throw err;
        }
        if (result) {
            jsonWrite(res, result);
        }
    })
});
//用户登录
router.post('/login', (req, res) => {
    let { Phone, userPwd } = req.body;
    const sqlStr = `select * from users where  Phone='${Phone}' and userPwd='${userPwd}'`
    conn.query(sqlStr, (err, result) => {
        if (err) {
            throw err;
        }
        if (result) {
            jsonWrite(res, result);
        }
    })
});
//账户密码修改
router.post('/updUserPwd', (req, res) => {
    let { userId, userPwd } = req.body;
    const sqlStr = `UPDATE users SET userPwd='${userPwd}'  WHERE userId='${userId}'`
    conn.query(sqlStr, (err, result) => {
        if (err) {
            throw err;
        }
        if (result) {
            jsonWrite(res, result);
        }
    })
})
module.exports = router;